package com.wkr.order.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

@Slf4j
@RefreshScope
@RestController
public class MailController {

    // nacos获取
    @Value("${mail.addr}")
    private String mail;

    // 此处密码为邮箱开启IMAP/SMTP服务后生成的授权码
    // 非邮箱登陆密码
    @Value("${mail.ps}")
    private String ps;


    @PostMapping("/alarm")
    public void sendAlarm(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Map<String, String[]> parameterMap = request.getParameterMap();

        for (Object o : parameterMap.keySet()) {
            System.out.println(o + ":" + parameterMap.get(o)[0]);
        }
        System.out.println(mail);
        try {
            HtmlEmail email = new HtmlEmail();
            email.setHostName("smtp.qq.com");
            email.setCharset("utf-8");
            email.addTo(parameterMap.get("to")[0]);
            email.setFrom(mail);
            email.setAuthentication(mail, ps);
            email.setSubject(parameterMap.get("value")[0].substring(0, 16));
            email.setMsg(parameterMap.get("value")[0]);
            email.send();
        } catch (EmailException e) {
            log.error(e.getMessage(), e);
        }
        response.setStatus(200);
        PrintWriter pw = response.getWriter();
        pw.write("200");
        pw.flush();
        pw.close();
    }

}
